from model import db
import datetime
from sqlalchemy.dialects.mysql import LONGTEXT
from model.tag import Tag

# 多对多关系中间辅助表
tags = db.Table('tags',
                db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
                db.Column('photo_id', db.Integer, db.ForeignKey('photo.id'), primary_key=True)
                )


class Photo(db.Model):
    __tablename__ = "photo"  # 映射的数据表，不写默认是类名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    photo_name = db.Column(db.String(128), nullable=False)
    content = db.Column(LONGTEXT, nullable=False)
    user_id = db.Column(db.Integer)
    photo_path = db.Column(db.String(512), nullable=False)
    user_ip = db.Column(db.String(128), nullable=False)
    load_time = db.Column(db.DateTime, default=datetime.datetime.now())
    category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False)
    like_count = db.Column(db.Integer, default=0)
    # 多对多关系，会关联到多对多关系中间辅助表tags
    tags = db.relationship("Tag", secondary=tags, lazy='subquery', backref=db.backref('photo', lazy=True))

    def keys(self):
        return ('id', 'photo_name', 'content', 'user_id', 'photo_path', 'user_ip', 'load_time', 'category_id', 'tags')

    def __getitem__(self, item):
        return getattr(self, item)


# def keys(self):
#     return ("id", 'category_id', 'photo_name', 'user_id', 'photo_path', 'user_ip', 'load_time')
#
#
# def __getitem__(self, item):
#     return getattr(self, item)
